package data

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"user/internal/biz"
)

type userRepo struct {
	data *Data
	log  *log.Helper
}

func (u userRepo) LoginUser(cxt context.Context, model *biz.Users) (uint, error) {
	//TODO implement me
	err := u.data.DataBase.Debug().Model(model).Where("name=?", model.Name).Find(model).Error
	if err != nil {
		return 0, err
	}
	return uint(model.Id), err
}

func (u userRepo) ListUser(cxt context.Context, page int64, size int64) (*[]biz.Users, error) {
	var user = []biz.Users{}
	pageSize := size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	err := u.data.DataBase.Debug().Model(&biz.Users{}).Offset(int(offset)).Limit(int(pageSize)).Find(&user).Error
	if err != nil {
		return nil, err
	}
	fmt.Printf("%v", user)
	return &user, nil
}

func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
	return &userRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}
func (u userRepo) CreateUser(cxt context.Context, model *biz.Users) (uint, error) {
	tx := u.data.DataBase.Create(model)
	if tx.Error != nil {
		return 0, tx.Error
	}
	return uint(model.Id), nil
}
